#!/bin/sh /etc/rc.common

START=99
STOP=10

EXTRA_COMMANDS="setLan"
EXTRA_HELP="set ULA and DHCPv6"

enable=$(uci get nat6-helper.@nat6-helper[0].enabled)
interface_public=$(uci get nat6-helper.@nat6-helper[0].name)

interface=$(uci get "network.$interface_public.ifname")             #获取选中的ipv6出口网口
last_if=$(ip6tables-save -t nat | grep "v6NAT" | awk '{print $4}')  #获取之前设置的出口网口
gateway=$(ip -6 route | grep "default from 2" | awk '{print $5}')   #获取当前网关
last_gw=$(ip -6 route | grep "2000::/3" | awk '{print $3}')         #之前的网关地址
#由于网络变动后网关可能会变，以及用户有可能重新选择出口网口，所以需要先获取之前的网关凑成删除命令
#原先的default via命令有可能会冲突，所以改用nat6脚本中的只路由到公网的ip，即2开头的ip

#一键设置函数
setLan() 
{
    #一键设置ULA和DHCPv6和ipv6 dns服务器
    # uci set network.globals.ula_prefix='fd00::/64'
    # uci set network.wan6.dns='2400:3200::1 2400:da00::6666'
    uci set network.globals.ula_prefix='fd00:6666:6666::/64'
    uci set network.wan6.dns='2001:4860:4860::8888 240c::6666'
    uci set network.wan6.peerdns='0'
    uci set network.wan6.reqaddress='try'
    uci set network.wan6.reqprefix='auto'
	uci set dhcp.lan.dhcpv6='server'
	uci set dhcp.lan.ra='server'
	uci set dhcp.lan.ra_default='1'
	uci set dhcp.lan.ra_management='1'
    uci delete dhcp.@dnsmasq[0].filter_aaaa
	uci commit network
	uci commit dhcp
    /etc/init.d/network restart
    logger -t nat6-helper "ULA and DHCPv6 have been set"
}

start()
{
	[ $enable = "0" ] && exit 0
    #设置最新网关
    ip -6 r add "2000::/3" via $gateway dev $interface > /dev/null 2>&1

    #设置nat6
    ip6tables -t nat -A POSTROUTING -o $interface -m comment --comment "v6NAT" -j MASQUERADE

    #向系统日志输出设置成功信息
    if (ip -6 route | grep -q "2000::/3") && (ip6tables-save -t nat | grep -q "v6NAT");then
        logger -t nat6-helper "Routing rule and firewall NAT6 rule have been set"
    fi
}

stop()
{
    #删除之前在路由表给想访问公网ip的数据包设置的路由器上级网关
    ip -6 r del "2000::/3" via $last_gw dev $last_if

    #删除nat6设置
    ip6tables -t nat -D POSTROUTING -o $last_if -m comment --comment "v6NAT" -j MASQUERADE

    #向系统日志输出清除设置成功信息
    if !(ip -6 route | grep -q "2000::/3") && !(ip6tables-save -t nat | grep -q "v6NAT");then
        logger -t nat6-helper "Routing rule and firewall NAT6 rule have been delete"
    fi
}